package com.scalar.chiptrack.operations.finishedGoods.actionCommands;

import com.scalar.chiptrack.ChipTrackExtendedAction;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.finishedGoods.forms.FinishedGoodsEntryForm;
import com.scalar.chiptrack.operations.finishedGoods.dao.FinishedGoodsDAO;
import com.scalar.chiptrack.operations.finishedGoods.EquivalentPartNumber;
import com.scalar.chiptrack.operations.finishedGoods.FinishedGoodsHelper;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.processtypesetup.dao.ProcessTypeSetupDAO;
import com.scalar.ScalarException;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * User: Murali Krishna Yengala
 * Date: May 29, 2005
 * Time: 10:28:43 AM
 */
public class FinishedGoodsNewConfirmCommand extends ChipTrackExtendedAction {
    
    public ActionForward executeRequest( ActionMapping mapping,
                                         ActionForm form,
                                         HttpServletRequest request,
                                         HttpServletResponse response) throws Exception
    {
        FinishedGoodsEntryForm finishedGoodsEntryForm = ( FinishedGoodsEntryForm ) form;
        HashMap errors              = ( HashMap ) request.getAttribute( ERROR_MESSAGES );
        HashMap info                = ( HashMap ) request.getAttribute( INFO_MESSAGES );

        String partNumberS = finishedGoodsEntryForm.getFinishedGoodsPartNo();
        int baseProductIdI = finishedGoodsEntryForm.getBaseProductIdI();
        FinishedGoodsHelper.setFgiProducts(baseProductIdI, request, errors, info );
        FinishedGoodsHelper.setCustomers( request, errors );
        finishedGoodsEntryForm.setVendorList( FinishedGoodsHelper.getVendorLocations( request));
        request.setAttribute( "units", ProcessTypeSetupDAO.getUnitsOfMesurment() );
        request.setAttribute( "algorithmList", FinishedGoodsDAO.loadAlgorithmList());
        
        try
        {
            boolean partNoPresent = FinishedGoodsDAO.checkForDuplicateValueInProductTable( partNumberS, -1, 1);
            boolean partNoPresentInMktgPartNo = FinishedGoodsDAO.checkForDuplicateValueInProductTable( partNumberS, -1, 2);
            if ( partNoPresent || partNoPresentInMktgPartNo )
            {
                errors.put ( "OPN / Mktg Part Number = "+partNumberS, " Already Exists" );
                request.setAttribute( SessionKeys.ERROR_MESSAGES, errors);
                return mapping.findForward("newEntry");
            }
        }
        catch( ScalarException e)
        {
            e.printStackTrace();
            errors.put ( ERROR_INTERNAL_SERVER_ERROR, "" );
            request.setAttribute( SessionKeys.ERROR_MESSAGES, errors);
            return mapping.findForward("newEntry");
        }

        String[] partNumbers = new String[ 1 ];
        partNumbers[ 0 ] = partNumberS;
        try
        {
            String dupNames = ProductDao.checkDupInProductMapTable ( partNumbers , -1 , Constants.LOCATION_TYPE_FINISHED_GOODS );
            if( dupNames != null && dupNames.length () > 0 )
            {
                errors.put ( "OPN / Mktg Part Number = "+partNumberS, " Already Exists" );
                request.setAttribute( SessionKeys.ERROR_MESSAGES, errors);
                return mapping.findForward("newEntry");
            }
        }
        catch( ScalarException e)
        {
            e.printStackTrace();
            errors.put ( ERROR_INTERNAL_SERVER_ERROR, "" );
            request.setAttribute( SessionKeys.ERROR_MESSAGES, errors);
            return mapping.findForward("newEntry");
        }

        String programCodeS = finishedGoodsEntryForm.getProgramCode();
        programCodeS = (programCodeS == null ? "" : programCodeS.trim());
        try
        {
            // -1 for 3rd parameter, because this is a new finished good  
            ArrayList fgiPartsAndCustomers = FinishedGoodsDAO.checkForProgramCodeDuplicates(programCodeS, finishedGoodsEntryForm.getCustomerIds(), -1, finishedGoodsEntryForm.getFgiProcessStepIds());
            if( fgiPartsAndCustomers != null && fgiPartsAndCustomers.size() > 0)
            {
                StringBuffer errorMsg = new StringBuffer("Already exists for the following Customer(s) and Blank FGI part Number(s)<tr class='NArialL'><td colspan='2'><font color='red'>");
                for( int i = 0; i < fgiPartsAndCustomers.size(); i++)
                {
                    errorMsg.append( "<li>"+fgiPartsAndCustomers.get(i) );
                }
                errors.put("Program Code = "+programCodeS, errorMsg.toString()+"</font></td></tr>");
                request.setAttribute( SessionKeys.ERROR_MESSAGES, errors);
                return mapping.findForward("newEntry");
            }
        }
        catch( ScalarException e)
        {
            e.printStackTrace();
            errors.put ( ERROR_INTERNAL_SERVER_ERROR, "" );
            request.setAttribute( SessionKeys.ERROR_MESSAGES, errors);
            return mapping.findForward("newEntry");
        }

        ArrayList dupPartNosArrayList = finishedGoodsEntryForm.getEquivalentPartNosList();
        if( dupPartNosArrayList != null)
        {
            Iterator dupPartsIterator = dupPartNosArrayList.iterator();
            while( dupPartsIterator.hasNext() )
            {
                EquivalentPartNumber dupPartNumber = ( EquivalentPartNumber) dupPartsIterator.next();
                String partNo = dupPartNumber.getPartNo();
                if(partNo==null ||  (partNo != null && "".equals(partNo.trim())))
                {
                    dupPartsIterator.remove();
                }
            }
            if( dupPartNosArrayList.size() == 0)
            {
                finishedGoodsEntryForm.setEquivalentPartNosList( null);
            }
            else
            {
                String[] dupPartNosArray = new String[dupPartNosArrayList.size()];
                dupPartsIterator = null;
                dupPartsIterator = dupPartNosArrayList.iterator();
                int idx = 0;
                while( dupPartsIterator.hasNext() )
                {
                    EquivalentPartNumber dupPartNumber = ( EquivalentPartNumber) dupPartsIterator.next();
                    String partNo = dupPartNumber.getPartNo();
                    if( partNo != null)
                    {
                        dupPartNosArray[idx++] = partNo.trim();
                    }
                }

                try
                {
                    String dupNames = ProductDao.checkDupInProductMapTable ( dupPartNosArray , -1 , Constants.LOCATION_TYPE_FINISHED_GOODS );
                    if( dupNames != null && dupNames.length () > 0 )
                    {
                        errors.put ( "Equivalent Part Numbers = "+dupNames, " Already Exists" );
                        request.setAttribute( SessionKeys.ERROR_MESSAGES, errors);
                        return mapping.findForward("newEntry");
                    }
                }
                catch( Exception e)
                {
                    e.printStackTrace();
                    errors.put ( ERROR_INTERNAL_SERVER_ERROR, "" );
                    request.setAttribute( SessionKeys.ERROR_MESSAGES, errors);
                    return mapping.findForward("newEntry");
                }
            }
        }
        request.setAttribute( SessionKeys.INFO_MESSAGES, info);
        request.setAttribute( SessionKeys.ERROR_MESSAGES, info);
        return mapping.findForward("view");
    }
}
